#include "log.h"
#include <pthread.h>
#include <string>
#include <sstream>

using namespace std;

Log* Log::instance = NULL;
int Log::reference_count = 0;

Log::Log()
{

}

Log::~Log()
{

}

void Log::destroy()
{
    delete instance;
    instance = NULL;
    outfile.close();
}

void Log::init()
{
    outfile.open("./error_log.txt");
}

void Log::mutexLock()
{
  pthread_mutex_lock(&theMutex);
}

void Log::mutexUnlock()
{
  pthread_mutex_unlock(&theMutex);
}

Log* Log::getInstance()
{
    if(instance == NULL)
    {
        instance = new Log;
        instance->init();
    }
    ++reference_count;
    return instance;
}

void Log::logMessageCreate(int id)
{
    string input = "";
    stringstream ss;
    ss << id;
    ss >> input;
    logMessage("[Normal] Thread " + input + " created.");
}

void Log::logMessageExit(int id)
{
    string input = "";
    stringstream ss;
    ss << id;
    ss >> input;
    logMessage("[Normal] Thread " + input + " exits.");
}

void Log::logMessageExitFail(int id, string message)
{
    string input = "";
    stringstream ss;
    ss << id;
    ss >> input;
    logMessage("[Failure] Thread " + input + " exits " + message);
}

void Log::logMessageWarning(string message)
{

    logMessage("[Warning] " + message );
}

void Log::release()
{
    if( --reference_count < 1 )
    {
        destroy();
    }

}

void Log::logMessage(string message)
{
    mutexLock();
    outfile << message << endl;
    mutexUnlock();
}

pthread_mutex_t* Log::getMutex()
{
    return &theMutex;
}
